package com.leetcode.partition7;

import com.leetcode.common.TreeNode;

import java.util.LinkedList;

/**
 * @author `RKC`
 * @date 2021/8/20 9:03
 */
public class LC617合并二叉树 {

    public static TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        return recursion(root1, root2);
    }

    public static void main(String[] args) {
        TreeNode r1 = new TreeNode(1, new TreeNode(3, new TreeNode(5), null), new TreeNode(2));
        TreeNode r2 = new TreeNode(2, new TreeNode(1, null, new TreeNode(4)), new TreeNode(3, null, new TreeNode(7)));
        TreeNode res = mergeTrees(r1, r2);
        System.out.println(res.val);
    }

    private static TreeNode bfs(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        if (root2 == null) return root1;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root1);
        queue.add(root2);
        while (!queue.isEmpty()) {
            TreeNode cur1 = queue.pollFirst();
            TreeNode cur2 = queue.pollFirst();
            cur1.val += cur2.val;
            if (cur1.left != null && cur2.left != null) {
                queue.add(cur1.left);
                queue.add(cur2.left);
            }
            if (cur1.right != null && cur2.right != null) {
                queue.add(cur1.right);
                queue.add(cur2.right);
            }
            if (cur1.left == null && cur2.left != null) {
                cur1.left = cur2.left;
            }
            if (cur1.right == null && cur2.right != null) {
                cur1.right = cur2.right;
            }
        }
        return root1;
    }

    private static TreeNode recursion(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 != null) return root2;
        if (root1 != null && root2 == null) return root1;
        if (root1 == null) return null;
        root1.val += root2.val;
        root1.left = recursion(root1.left, root2.left);
        root1.right = recursion(root1.right, root2.right);
        return root1;
    }
}
